package com.seu.vcampus.view;

import com.seu.vcampus.client.VCampusClient;
import com.seu.vcampus.message.Message;
import com.seu.vcampus.util.UIStyleUtil;
import com.seu.vcampus.vo.User;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

/**
 * 现代化登录界面
 * 采用Material Design风格，提供用户登录和注册功能
 * 
 * @author 虚拟校园开发团队
 * @since 2.0.0
 */
public class ModernLoginFrame extends JFrame {
    private VCampusClient client;
    
    // 登录组件
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton loginButton;
    private JButton registerButton;
    private JCheckBox rememberMeCheckBox;
    private JLabel statusLabel;
    
    // 注册组件（在注册面板中）
    private JTextField regUsernameField;
    private JPasswordField regPasswordField;
    private JPasswordField regConfirmPasswordField;
    private JTextField regEmailField;
    private JTextField regPhoneField;
    private JComboBox<String> regUserTypeComboBox;
    
    // 卡片布局
    private CardLayout cardLayout;
    private JPanel mainPanel;
    
    public ModernLoginFrame(VCampusClient client) {
        super("虚拟校园系统 - 登录");
        this.client = client;
        
        UIStyleUtil.setupGlobalStyle();
        initializeComponents();
        setupLayout();
        setupEventHandlers();
        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(550, 700); // 增大窗口尺寸
        setLocationRelativeTo(null);
        setResizable(false);
    }
    
    /**
     * 初始化所有组件
     */
    private void initializeComponents() {
        // 登录组件
        usernameField = UIStyleUtil.createModernTextField("用户名");
        passwordField = UIStyleUtil.createModernPasswordField("密码");
        loginButton = UIStyleUtil.createSuccessButton("登录");
        registerButton = UIStyleUtil.createPrimaryButton("注册新账号");
        rememberMeCheckBox = new JCheckBox("记住我");
        rememberMeCheckBox.setFont(UIStyleUtil.BODY_FONT);
        rememberMeCheckBox.setBackground(Color.WHITE);
        statusLabel = UIStyleUtil.createModernLabel("请输入用户名和密码", UIStyleUtil.BODY_FONT, UIStyleUtil.SECONDARY_COLOR);
        
        // 注册组件
        regUsernameField = UIStyleUtil.createModernTextField("用户名");
        regPasswordField = UIStyleUtil.createModernPasswordField("密码");
        regConfirmPasswordField = UIStyleUtil.createModernPasswordField("确认密码");
        regEmailField = UIStyleUtil.createModernTextField("邮箱");
        regPhoneField = UIStyleUtil.createModernTextField("电话");
        
        String[] userTypes = {"学生", "教师"};
        regUserTypeComboBox = new JComboBox<>(userTypes);
        regUserTypeComboBox.setFont(UIStyleUtil.BODY_FONT);
        regUserTypeComboBox.setBackground(Color.WHITE);
        
        // 卡片布局
        cardLayout = new CardLayout();
        mainPanel = new JPanel(cardLayout);
        mainPanel.setBackground(Color.WHITE);
    }
    
    /**
     * 设置布局
     */
    private void setupLayout() {
        // 创建登录面板
        JPanel loginPanel = createLoginPanel();
        
        // 创建注册面板
        JPanel registerPanel = createRegisterPanel();
        
        // 添加到卡片布局
        mainPanel.add(loginPanel, "login");
        mainPanel.add(registerPanel, "register");
        
        add(mainPanel);
    }
    
    /**
     * 创建登录面板
     */
    private JPanel createLoginPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBackground(Color.WHITE);
        panel.setBorder(new EmptyBorder(40, 40, 40, 40));
        
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        // Logo
        JLabel logoLabel = new JLabel("虚拟校园", JLabel.CENTER);
        logoLabel.setFont(new Font("微软雅黑", Font.BOLD, 32));
        logoLabel.setForeground(UIStyleUtil.PRIMARY_COLOR);
        
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.insets = new Insets(0, 0, 30, 0);
        panel.add(logoLabel, gbc);
        
        // 用户名标签和输入框
        gbc.gridwidth = 1;
        gbc.gridy = 1;
        gbc.insets = new Insets(5, 5, 5, 5);
        JLabel usernameLabel = new JLabel("用户名:");
        usernameLabel.setForeground(Color.BLACK);
        panel.add(usernameLabel, gbc);
        
        gbc.gridx = 1;
        panel.add(usernameField, gbc);
        
        // 密码标签和输入框
        gbc.gridx = 0;
        gbc.gridy = 2;
        JLabel passwordLabel = new JLabel("密码:");
        passwordLabel.setForeground(Color.BLACK);
        panel.add(passwordLabel, gbc);
        
        gbc.gridx = 1;
        panel.add(passwordField, gbc);
        
        // 记住我复选框
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        panel.add(rememberMeCheckBox, gbc);
        
        // 登录按钮
        gbc.gridy = 4;
        gbc.insets = new Insets(15, 5, 5, 5);
        loginButton.setPreferredSize(new Dimension(0, 40));
        panel.add(loginButton, gbc);
        
        // 注册按钮
        gbc.gridy = 5;
        gbc.insets = new Insets(10, 5, 5, 5);
        registerButton.setPreferredSize(new Dimension(0, 35));
        panel.add(registerButton, gbc);
        
        // 状态标签
        gbc.gridy = 6;
        gbc.insets = new Insets(10, 5, 0, 5);
        panel.add(statusLabel, gbc);
        
        return panel;
    }
    
    /**
     * 创建注册面板
     */
    private JPanel createRegisterPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBackground(Color.WHITE);
        panel.setBorder(new EmptyBorder(30, 40, 30, 40));
        
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(3, 3, 3, 3);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        // Logo
        JLabel logoLabel = new JLabel("注册新账号", JLabel.CENTER);
        logoLabel.setFont(new Font("微软雅黑", Font.BOLD, 28));
        logoLabel.setForeground(UIStyleUtil.PRIMARY_COLOR);
        
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.gridwidth = 2;
        gbc.insets = new Insets(0, 0, 20, 0);
        panel.add(logoLabel, gbc);
        
        // 用户名
        gbc.gridwidth = 1;
        gbc.gridy = 1;
        JLabel usernameLabel2 = new JLabel("用户名:");
        usernameLabel2.setForeground(Color.BLACK);
        panel.add(usernameLabel2, gbc);
        
        gbc.gridx = 1;
        panel.add(regUsernameField, gbc);
        
        // 密码
        gbc.gridx = 0;
        gbc.gridy = 2;
        JLabel passwordLabel2 = new JLabel("密码:");
        passwordLabel2.setForeground(Color.BLACK);
        panel.add(passwordLabel2, gbc);
        
        gbc.gridx = 1;
        panel.add(regPasswordField, gbc);
        
        // 确认密码
        gbc.gridx = 0;
        gbc.gridy = 3;
        JLabel confirmPasswordLabel = new JLabel("确认密码:");
        confirmPasswordLabel.setForeground(Color.BLACK);
        panel.add(confirmPasswordLabel, gbc);
        
        gbc.gridx = 1;
        panel.add(regConfirmPasswordField, gbc);
        
        // 邮箱
        gbc.gridx = 0;
        gbc.gridy = 4;
        JLabel emailLabel = new JLabel("邮箱:");
        emailLabel.setForeground(Color.BLACK);
        panel.add(emailLabel, gbc);
        
        gbc.gridx = 1;
        panel.add(regEmailField, gbc);
        
        // 电话
        gbc.gridx = 0;
        gbc.gridy = 5;
        JLabel phoneLabel = new JLabel("电话:");
        phoneLabel.setForeground(Color.BLACK);
        panel.add(phoneLabel, gbc);
        
        gbc.gridx = 1;
        panel.add(regPhoneField, gbc);
        
        // 用户类型
        gbc.gridx = 0;
        gbc.gridy = 6;
        JLabel userTypeLabel = new JLabel("用户类型:");
        userTypeLabel.setForeground(Color.BLACK);
        panel.add(userTypeLabel, gbc);
        
        gbc.gridx = 1;
        panel.add(regUserTypeComboBox, gbc);
        
        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 10, 0));
        buttonPanel.setOpaque(false);
        
        JButton registerConfirmButton = UIStyleUtil.createSuccessButton("注册");
        JButton backToLoginButton = UIStyleUtil.createSecondaryButton("返回登录");
        
        buttonPanel.add(registerConfirmButton);
        buttonPanel.add(backToLoginButton);
        
        gbc.gridx = 0;
        gbc.gridy = 7;
        gbc.gridwidth = 2;
        gbc.insets = new Insets(15, 5, 5, 5);
        panel.add(buttonPanel, gbc);
        
        // 注册事件
        registerConfirmButton.addActionListener(e -> performRegister());
        backToLoginButton.addActionListener(e -> showLoginPanel());
        
        return panel;
    }
    
    /**
     * 设置事件处理器
     */
    private void setupEventHandlers() {
        // 登录事件
        loginButton.addActionListener(e -> performLogin());
        registerButton.addActionListener(e -> showRegisterPanel());
        
        // 回车键登录
        KeyAdapter loginKeyAdapter = new KeyAdapter() {
            public void keyPressed(KeyEvent e) {
                if (e.getKeyCode() == KeyEvent.VK_ENTER) {
                    performLogin();
                }
            }
        };
        usernameField.addKeyListener(loginKeyAdapter);
        passwordField.addKeyListener(loginKeyAdapter);
        
        // ESC键关闭
        getRootPane().registerKeyboardAction(
            e -> dispose(),
            KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
            JComponent.WHEN_IN_FOCUSED_WINDOW
        );
    }
    
    /**
     * 执行登录
     */
    private void performLogin() {
        String username = usernameField.getText().trim();
        String password = new String(passwordField.getPassword());
        
        if (username.isEmpty() || password.isEmpty()) {
            statusLabel.setText("请输入用户名和密码");
            return;
        }
        
        loginButton.setEnabled(false);
        statusLabel.setText("正在登录...");
        
        new Thread(() -> {
            try {
                Message request = new Message(Message.Type.LOGIN_REQUEST);
                User loginUser = new User();
                loginUser.setUsername(username);
                loginUser.setPassword(password);
                request.setPayload(loginUser);
                Message response = client.sendMessage(request);
                
                SwingUtilities.invokeLater(() -> {
                    if (response.isSuccess()) {
                        User user = (User) response.getPayload();
                        loginSuccess(user);
                    } else {
                        loginFailed(response.getErrorMessage());
                    }
                });
                
            } catch (Exception e) {
                SwingUtilities.invokeLater(() -> {
                    loginFailed("登录失败: " + e.getMessage());
                });
            }
        }).start();
    }
    
    /**
     * 登录成功
     */
    private void loginSuccess(User user) {
        dispose();
        
        ModernMainFrame mainFrame = new ModernMainFrame(client, user);
        mainFrame.setVisible(true);
    }
    
    /**
     * 登录失败
     */
    private void loginFailed(String errorMessage) {
        loginButton.setEnabled(true);
        statusLabel.setText(errorMessage);
        passwordField.setText("");
    }
    
    /**
     * 执行注册
     */
    private void performRegister() {
        String username = regUsernameField.getText().trim();
        String password = new String(regPasswordField.getPassword());
        String confirmPassword = new String(regConfirmPasswordField.getPassword());
        String email = regEmailField.getText().trim();
        String phone = regPhoneField.getText().trim();
        String userTypeText = regUserTypeComboBox.getSelectedItem().toString();
        
        // 输入验证
        if (username.isEmpty() || password.isEmpty()) {
            JOptionPane.showMessageDialog(this, "用户名和密码不能为空", 
                                        "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        if (!password.equals(confirmPassword)) {
            JOptionPane.showMessageDialog(this, "两次输入的密码不一致", 
                                        "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        if (password.length() < 6) {
            JOptionPane.showMessageDialog(this, "密码长度至少6位", 
                                        "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        if (!email.isEmpty() && !isValidEmail(email)) {
            JOptionPane.showMessageDialog(this, "请输入有效的邮箱地址", 
                                        "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        if (!phone.isEmpty() && !isValidPhone(phone)) {
            JOptionPane.showMessageDialog(this, "请输入有效的电话号码", 
                                        "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }
        
        // 注册用户
        User.UserType userType = userTypeText.equals("学生") ? 
                               User.UserType.STUDENT : User.UserType.TEACHER;
        
        User newUser = new User();
        newUser.setUsername(username);
        newUser.setPassword(password);
        newUser.setEmail(email.isEmpty() ? null : email);
        newUser.setPhone(phone.isEmpty() ? null : phone);
        newUser.setUserType(userType);
        
        // 发送注册请求
        new Thread(() -> {
            try {
                Message request = new Message(Message.Type.REGISTER_REQUEST);
                request.setPayload(newUser);
                Message response = client.sendMessage(request);
                
                SwingUtilities.invokeLater(() -> {
                    if (response.isSuccess()) {
                        JOptionPane.showMessageDialog(this, "注册成功，请登录", 
                                                    "成功", JOptionPane.INFORMATION_MESSAGE);
                        showLoginPanel();
                        clearRegisterFields();
                    } else {
                        JOptionPane.showMessageDialog(this, "注册失败: " + response.getErrorMessage(), 
                                                    "错误", JOptionPane.ERROR_MESSAGE);
                    }
                });
                
            } catch (Exception e) {
                SwingUtilities.invokeLater(() -> {
                    JOptionPane.showMessageDialog(this, "注册失败: " + e.getMessage(), 
                                                "错误", JOptionPane.ERROR_MESSAGE);
                });
            }
        }).start();
    }
    
    /**
     * 显示登录面板
     */
    private void showLoginPanel() {
        cardLayout.show(mainPanel, "login");
    }
    
    /**
     * 显示注册面板
     */
    private void showRegisterPanel() {
        cardLayout.show(mainPanel, "register");
    }
    
    /**
     * 清空注册字段
     */
    private void clearRegisterFields() {
        regUsernameField.setText("");
        regPasswordField.setText("");
        regConfirmPasswordField.setText("");
        regEmailField.setText("");
        regPhoneField.setText("");
        regUserTypeComboBox.setSelectedIndex(0);
    }
    
    /**
     * 验证邮箱格式
     */
    private boolean isValidEmail(String email) {
        return email.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$");
    }
    
    /**
     * 验证电话号码格式
     */
    private boolean isValidPhone(String phone) {
        return phone.matches("^1[3-9]\\d{9}$");
    }
    
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            VCampusClient client = new VCampusClient("localhost", 8888);
            if (client.connect()) {
                ModernLoginFrame loginFrame = new ModernLoginFrame(client);
                loginFrame.setVisible(true);
            } else {
                JOptionPane.showMessageDialog(null, "无法连接到服务器", 
                                            "连接失败", JOptionPane.ERROR_MESSAGE);
            }
        });
    }
}